package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// TokenRequest 用于获取token的请求结构体
type TokenRequest struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	Code         string `json:"code,omitempty"`          // code用于获取token
	GrantType    string `json:"grant_type,omitempty"`    // grant_type用于刷新token
	RefreshToken string `json:"refresh_token,omitempty"` // refresh_token用于刷新token
}

// TokenResponse 用于解析token的响应结构体
type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token,omitempty"` // 可选，只有在成功获取token时存在
	TokenType    string `json:"token_type,omitempty"`
	Error        string `json:"error,omitempty"`
}

// 获取token
func GetToken(url, clientID, clientSecret, code string) (*TokenResponse, error) {
	data := TokenRequest{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		Code:         code,
	}

	return SendTokenRequest(url, data)
}

// 刷新token
func RefreshToken(url, clientID, clientSecret, refreshToken string) (*TokenResponse, error) {
	data := TokenRequest{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		GrantType:    "refresh_token",
		RefreshToken: refreshToken,
	}

	return SendTokenRequest(url, data)
}

// 发送token请求
func SendTokenRequest(url string, data TokenRequest) (*TokenResponse, error) {
	jsonData, err := json.Marshal(data)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal request data: %w", err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, fmt.Errorf("failed to create request: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %w", err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %w", err)
	}

	var keyValue map[string]interface{}
	err = json.Unmarshal(body, &keyValue)
	if err == nil {
		fmt.Printf("%v\n", keyValue)
	}

	// 解析响应
	var tokenResponse TokenResponse
	if err := json.Unmarshal(body, &tokenResponse); err != nil {
		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
	}

	// 检查错误
	if tokenResponse.Error != "" {
		return nil, fmt.Errorf("error response: %s", tokenResponse.Error)
	}

	return &tokenResponse, nil
}
